/**
 * Project 68th
 */


#include "../include/EchoServer.h"
#include "../include/MyTask.h"
#include "../include/log4cppuse.h"

/**
 * EchoServer implementation
 */


/**
 * @param threadNum
 * @param queSize
 * @param ip
 * @param port
 */
EchoServer::EchoServer(size_t threadNum, size_t queSize, const string& ip, unsigned short port) 
: _pool(threadNum,queSize)
, _server(ip,port)
{

}

EchoServer::~EchoServer() {

}

/**
 * @return void
 */
void EchoServer::start() {
   _pool.start();

   using namespace std::placeholders;
   _server.setAllCallback(bind(&EchoServer::OnNewConnection,this,_1),
                          bind(&EchoServer::OnMessage,this,_1),
                          bind(&EchoServer::OnClose,this,_1));

   _server.start();
}

/**
 * @return void
 */
void EchoServer::stop() {
    _pool.stop();
    _server.stop();
}

void EchoServer::OnNewConnection(const TcpConnectionPtr & con)
{
    string log=con->toString()+" has connected!";
    cout << log << endl;
    LOG_INFO(log.c_str());
}

void EchoServer::OnMessage(const TcpConnectionPtr & con)
{
    
    Message readmessage = con->receiveMessage();
    string log=con->toString()+" 发送标志 tag: "+to_string(readmessage.atg)+" and 消息长度 length: "+to_string(readmessage.length);
    cout << log << endl;
    LOG_DEBUG(log.c_str());
    // 处理空消息
    if(readmessage.isEmpty())
    {
        string log=con->toString()+" 发送空消息!";
        cout << log << endl;
        LOG_ERROR(log.c_str());
        return;
    }

    log=con->toString()+" 发送标志 tag: "+to_string(readmessage.atg)+" and 消息内容 message: "+readmessage.msg;
    cout << log << endl;
    LOG_INFO(log.c_str());

    MyTask ta(readmessage,con);
    _pool.addTask(std::bind(&MyTask::process,ta));
}

void EchoServer::OnClose(const TcpConnectionPtr & con)
{
    string log=con->toString()+" has closed!";
    cout << log << endl;
    LOG_INFO(log.c_str());
}
